package com.zsx.shopping.common.handler;

import com.zsx.shopping.common.enums.CodeMsg;
import com.zsx.shopping.common.exception.ShoppingException;
import com.zsx.shopping.common.api.R;
import feign.RetryableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R<Void> error(Exception e) {
        if (e instanceof ShoppingException) {
            ShoppingException exception = (ShoppingException) e;
            return R.fail(exception.getCode(), exception.getMsg());
        }
        if (e instanceof BindException || e instanceof MethodArgumentNotValidException) {
            FieldError fieldError;
            if (e instanceof BindException) {
                fieldError = ((BindException) e).getBindingResult().getFieldError();
            } else {
                fieldError = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError();
            }
            Integer code = CodeMsg.INVALID_PARAM.getCode();
            String msg = fieldError == null ? CodeMsg.INVALID_PARAM.getMsg() : fieldError.getDefaultMessage();
            return R.fail(code, msg);
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            CodeMsg codeMsg = CodeMsg.INVALID_PARAM;
            return R.fail(codeMsg.getCode(), codeMsg.getMsg());
        }
        if (e instanceof RetryableException) {
            CodeMsg codeMsg = CodeMsg.BUSY;
            return R.fail(codeMsg.getCode(), codeMsg.getMsg());
        }
        e.printStackTrace();
        CodeMsg codeMsg = CodeMsg.ERROR;
        return R.fail(codeMsg.getCode(), codeMsg.getMsg());
    }
}
